package com.common.dingding.controller;

import com.common.dingding.common.Result;
import com.common.dingding.service.DingTalkService;
import com.common.dingding.utils.JwtUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 钉钉登录控制器
 * 处理钉钉企业内部应用免登功能
 */
@RestController
@RequestMapping("/dingtalk")
public class DingTalkController {

    @Autowired
    private DingTalkService dingTalkService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 钉钉企业内部应用免登接口
     * 接收前端通过dd.config获取的免登授权码
     * @param code 免登授权码
     * @return 包含token和用户信息的响应
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> loginByAuthCode(@RequestParam("code") String code) {
        try {
            // 通过免登授权码获取钉钉用户信息
            Map<String, Object> userInfo = dingTalkService.getUserInfoByAuthCode(code);
            // 基于钉钉用户信息生成JWT token
            String token = jwtUtils.generateTokenByDingTalkUser(userInfo);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userInfo", userInfo);
            
            return Result.success(data, "登录成功");
        } catch (Exception e) {
            return Result.fail("登录失败: " + e.getMessage());
        }
    }

    /**
     * 获取钉钉JSAPI签名配置
     * 用于前端调用钉钉JSAPI
     * @param url 当前页面URL
     * @return JSAPI配置信息
     */
    @GetMapping("/jsapi-config")
    public Result<Map<String, Object>> getJsapiConfig(@RequestParam("url") String url) {
        try {
            // 这里应该实现获取JSAPI签名的逻辑
            // 实际应用中需要根据钉钉文档实现sign生成
            Map<String, Object> jsapiConfig = new HashMap<>();
            jsapiConfig.put("appId", ""); // 应该从配置中获取
            jsapiConfig.put("timestamp", ""); // 当前时间戳
            jsapiConfig.put("nonceStr", ""); // 随机字符串
            jsapiConfig.put("signature", ""); // 签名
            
            return Result.success(jsapiConfig, "获取JSAPI配置成功");
        } catch (Exception e) {
            return Result.fail("获取JSAPI配置失败: " + e.getMessage());
        }
    }

    /**
     * 验证token是否有效
     * @param token JWT token
     * @return 验证结果
     */
    @PostMapping("/verify-token")
    public Result<Map<String, Object>> verifyToken(@RequestParam("token") String token) {
        try {
            boolean isValid = jwtUtils.validateToken(token);
            if (isValid) {
                // 可以返回用户信息
                Map<String, Object> claims = jwtUtils.parseToken(token);
                Map<String, Object> data = new HashMap<>();
                data.put("userInfo", claims);
                return Result.success(data, "Token有效");
            } else {
                return Result.fail("Token无效");
            }
        } catch (Exception e) {
            return Result.fail("验证失败: " + e.getMessage());
        }
    }

    /**
     * 获取钉钉用户信息
     * @param authorization Authorization header
     * @return 用户信息
     */
    @GetMapping("/user-info")
    public Result<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String authorization) {
        try {
            // 从Authorization header中提取token
            String token = authorization.replace("Bearer ", "");
            
            // 解析token获取用户信息
            Map<String, Object> userInfo = jwtUtils.parseToken(token);
            
            return Result.success(userInfo, "获取用户信息成功");
        } catch (Exception e) {
            return Result.fail("获取用户信息失败: " + e.getMessage());
        }
    }
}